package com.nineclock.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nineclock.common.constant.SMSConstant;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.system.dto.SysRegisterDTO;
import com.nineclock.system.mapper.SysUserMapper;
import com.nineclock.system.pojo.SysUser;
import com.nineclock.system.service.SmsService;
import com.nineclock.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    SmsService smsService;

    @Override
    public Boolean checkExists(String mobile) {

        LambdaQueryWrapper<SysUser> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getMobile,mobile);
        Integer count = sysUserMapper.selectCount(queryWrapper);

        return count==1;
    }

    @Override
    public Long regiester(SysRegisterDTO sysRegisterDTO) {
        //参数校验
        if(sysRegisterDTO==null || StrUtil.isEmpty(sysRegisterDTO.getMobile()) || StrUtil.isEmpty(sysRegisterDTO.getCheckcode()) || StrUtil.isEmpty(sysRegisterDTO.getPassword())){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

//        对比验证码
        Boolean verify = smsService.verify(sysRegisterDTO.getMobile(), SMSConstant.SMS_TYPE_REGISTER, sysRegisterDTO.getCheckcode());
        if (!verify){
            throw new NcException(ResponseEnum.CODE_IMAGE_ERROR);
        }

//        保存注册信息
        SysUser sysUser=new SysUser();
        sysUser.setMobile(sysRegisterDTO.getMobile());
        sysUser.setPassword(new BCryptPasswordEncoder().encode(sysRegisterDTO.getPassword()));

        sysUserMapper.insert(sysUser);
//        删除redis验证码
        smsService.deleteSmsCode(sysRegisterDTO.getMobile(),SMSConstant.SMS_TYPE_REGISTER);
        return sysUser.getId();
    }
}
